package tma.sdcbatch11.foodordering;


import java.util.ArrayList;
import java.util.List;

import android.content.res.Configuration;
import android.annotation.SuppressLint;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;

import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.view.GestureDetector;

import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;

import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.animation.AnimationUtils;
import android.view.animation.Animation.AnimationListener;
import android.widget.AdapterView;


import android.widget.ListView;
import android.widget.ViewFlipper;

public class MainActivity extends ActionBarActivity {
	private IsAdapter adapter;
	private static final int SWIPE_MIN_DISTANCE = 120;
	private static final int SWIPE_THRESHOLD_VELOCITY = 200;
	private ViewFlipper mViewFlipper;	
	private AnimationListener mAnimationListener;
	private Context mContext;
	private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
    private ActionBarDrawerToggle mDrawerToggle;

    private CharSequence mDrawerTitle;
    private CharSequence mTitle;
    
    CustomDrawerAdapter adapterr;
    List<DrawerItem> dataList;
    
	@SuppressWarnings("deprecation")
	private final GestureDetector detector = new GestureDetector(new SwipeGestureDetector());
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        mContext = this;
		mViewFlipper = (ViewFlipper) this.findViewById(R.id.viewFlipper_main);
		mViewFlipper.setAutoStart(true);
		mViewFlipper.setFlipInterval(4000);
		mViewFlipper.startFlipping();
		mViewFlipper.setOnTouchListener(new FlipperTouchListener());	        
		
        ItemKindOfDish[] list = createList();		
		ListView listView = (ListView) findViewById(R.id.list_store_View);
		adapter = new IsAdapter(this, list);
		listView.setAdapter(adapter);
		listView.setOnItemClickListener(new StoreItemClickListener());
		
		findViewById(R.id.textView1).setOnClickListener(new DetailClickListener());
		 //Initializing
		dataList = new ArrayList<DrawerItem>();
		
		mTitle = mDrawerTitle = getTitle();

		mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.left_drawer);
        // set a custom shadow that overlays the main content when the drawer opens
        mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
     // Add Drawer Item to dataList
     		dataList.add(new DrawerItem(true));

     		dataList.add(new DrawerItem("Normal")); // adding a header to the list
     		dataList.add(new DrawerItem("Sign In", R.drawable.ic_action_email));
     		dataList.add(new DrawerItem("Promotions",R.drawable.ic_action_good));
     		
     		dataList.add(new DrawerItem("The Best"));// adding a header to the list
     		dataList.add(new DrawerItem("Store",R.drawable.ic_action_search));
     		dataList.add(new DrawerItem("Dish",R.drawable.ic_action_search));
     		adapterr = new CustomDrawerAdapter(this, R.layout.custom_drawer_item,
    				dataList);
        // set up the drawer's list view with items and click listener
     		mDrawerList.setAdapter(adapterr);
     		mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
        // enable ActionBar app icon to behave as action to toggle nav drawer
        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setHomeButtonEnabled(true);
     // ActionBarDrawerToggle ties together the the proper interactions
        // between the sliding drawer and the action bar app icon
        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
				R.drawable.ic_drawer, R.string.drawer_open,
				R.string.drawer_close) {
			public void onDrawerClosed(View view) {
				getActionBar().setTitle(mTitle);
				invalidateOptionsMenu(); // creates call to
											// onPrepareOptionsMenu()
			}

            public void onDrawerOpened(View drawerView) {
                getActionBar().setTitle(mDrawerTitle);
                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
            }
        };
        mDrawerLayout.setDrawerListener(mDrawerToggle);

		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.menu_icon, menu);
		return true;
	}
	/* Called whenever we call invalidateOptionsMenu() 
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        // If the nav drawer is open, hide action items related to the content view
        boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
        menu.findItem(R.id.action_search).setVisible(!drawerOpen);
        return super.onPrepareOptionsMenu(menu);
    }*/
	public void SelectItem(int possition) {

		Fragment fragment = null;
		Bundle args = new Bundle();
		switch (possition) {
		case 1:
			fragment = new FragmentTwo();
			args.putString(FragmentTwo.ITEM_NAME, dataList.get(possition)
					.getItemName());
			args.putInt(FragmentTwo.IMAGE_RESOURCE_ID, dataList
					.get(possition).getImgResID());
			break;
		case 2:
			fragment = new FragmentThree();
			args.putString(FragmentThree.ITEM_NAME, dataList.get(possition)
					.getItemName());
			args.putInt(FragmentThree.IMAGE_RESOURCE_ID, dataList
					.get(possition).getImgResID());
			break;
		case 3:
			fragment = new FragmentOne();
			args.putString(FragmentOne.ITEM_NAME, dataList.get(possition)
					.getItemName());
			args.putInt(FragmentOne.IMAGE_RESOURCE_ID, dataList.get(possition)
					.getImgResID());
			break;
		case 4:
			fragment = new FragmentTwo();
			args.putString(FragmentTwo.ITEM_NAME, dataList.get(possition)
					.getItemName());
			args.putInt(FragmentTwo.IMAGE_RESOURCE_ID, dataList.get(possition)
					.getImgResID());
			break;
		case 5:
			fragment = new FragmentThree();
			args.putString(FragmentThree.ITEM_NAME, dataList.get(possition)
					.getItemName());
			args.putInt(FragmentThree.IMAGE_RESOURCE_ID, dataList
					.get(possition).getImgResID());
			break;
		case 6:
			fragment = new FragmentOne();
			args.putString(FragmentOne.ITEM_NAME, dataList.get(possition)
					.getItemName());
			args.putInt(FragmentOne.IMAGE_RESOURCE_ID, dataList
					.get(possition).getImgResID());
			break;
		default:
			break;
		}

		fragment.setArguments(args);
		FragmentManager frgManager = getFragmentManager();
		//frgManager.beginTransaction().replace(R.id.activity_main, fragment).commit();
		frgManager.beginTransaction().replace(R.id.content_Relative, fragment).commit();
		
		//FragmentTransaction transaction = frgManager.beginTransaction();
		//transaction.replace(R.id.content_Relative, fragment);
		//transaction.addToBackStack(null);
		//transaction.commit();
		
		mDrawerList.setItemChecked(possition, true);
		setTitle(dataList.get(possition).getItemName());
		mDrawerLayout.closeDrawer(mDrawerList);

	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
		switch(item.getItemId()){
		case R.id.action_cart:
			Intent nextScreen = new Intent(getApplicationContext(),
					Cart_turn_page.class);
			startActivity(nextScreen);
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}
	//The touch in ViewFlipper 
	@SuppressLint("ClickableViewAccessibility")
	private class FlipperTouchListener implements ListView.OnTouchListener{
		@Override
		public boolean onTouch(View v, MotionEvent event) {
			detector.onTouchEvent(event);
			return true;
		}
	}
	
	class SwipeGestureDetector extends SimpleOnGestureListener {
		@Override
		public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
			try {
				// right to left swipe
				if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
					mViewFlipper.setInAnimation(AnimationUtils.loadAnimation(mContext, R.anim.left_in));
					mViewFlipper.setOutAnimation(AnimationUtils.loadAnimation(mContext, R.anim.left_out));
					// controlling animation
					mViewFlipper.getInAnimation().setAnimationListener(mAnimationListener);
					mViewFlipper.showNext();
					return true;
				} else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
					mViewFlipper.setInAnimation(AnimationUtils.loadAnimation(mContext, R.anim.right_in));
					mViewFlipper.setOutAnimation(AnimationUtils.loadAnimation(mContext,R.anim.right_out));
					// controlling animation
					mViewFlipper.getInAnimation().setAnimationListener(mAnimationListener);
					mViewFlipper.showPrevious();
					return true;
				} 
				
			} catch (Exception e) {
				e.printStackTrace();
			}
			return false;
		}
	}
	// The click listener for View in Detail
	private class DetailClickListener implements ListView.OnClickListener{
		@Override
		public void onClick(View v) {
			Intent nextScreen = new Intent(getApplicationContext(), DishDetail.class);
			startActivity(nextScreen);		
				
		}
	}
	// The click listener for ListView in Store List
	private class StoreItemClickListener implements ListView.OnItemClickListener{
		@Override	
		public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
			ItemKindOfDish item = adapter.getItem(position);
					
			Intent itent = new Intent(getApplicationContext(), List_dish.class);
			itent.putExtra("item", item);
			startActivity(itent);				
		}
	}
		
	public ItemKindOfDish[]createList(){
		ItemKindOfDish[] items = new ItemKindOfDish[4];
		String[] name = getResources().getStringArray(R.array.listtypedish);
		String[] rate = getResources().getStringArray(R.array.rate);
		String[] address = getResources().getStringArray(R.array.address);
			
		for(int i = 0; i < items.length; i++){
				items[i] = new ItemKindOfDish(name[i], rate[i], address[i]);
		}
		return items;
	}
		
	/* The click listner for ListView in the navigation drawer */

	private class DrawerItemClickListener implements
	ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
		long id) {
	if (dataList.get(position).getTitle() == null) {
		SelectItem(position);
	}

}
}
	@Override
    public void setTitle(CharSequence title) {
        mTitle = title;
        getActionBar().setTitle(mTitle);
    }
	/**
     * When using the ActionBarDrawerToggle, you must call it during
     * onPostCreate() and onConfigurationChanged()...
     */

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        mDrawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // Pass any configuration change to the drawer toggls
        mDrawerToggle.onConfigurationChanged(newConfig);
    }
    
	/**
     * Fragment that appears in the "content_frame", shows a planet
     */
 
}
